package iot.jtt808;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Created by dave on 18-7-15 下午3:15.
 * JTT808协议拆包
 */
public class FrameDecoder extends ByteToMessageDecoder {
    private static final Logger L = LoggerFactory.getLogger(FrameDecoder.class);
    private static final byte DELIMITER = 0x7e;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() > 2 * 1024 * 1024) { //大于2M 直接丢弃
            in.skipBytes(in.readableBytes());
            return;
        }

        int start = in.readerIndex();
        int end = in.indexOf(start + 1, in.writerIndex(), DELIMITER);
        if (in.getByte(start) == DELIMITER) {
            if (end > 0) {
                int size = end - start + 1;
                byte[] bytes = new byte[size];
                in.readBytes(bytes);
                out.add(bytes);
            }
        } else {
            if (end > 0) {
                byte[] bytes = new byte[end - start];
                in.readBytes(bytes);
                L.warn("丢弃1 " + (end - start) + ": " + javax.xml.bind.DatatypeConverter.printHexBinary(bytes));
            } else {
                int size = in.readableBytes();
                if (size > 0) {
                    in.skipBytes(size);
                    L.warn("丢弃2 " + size);
                }
            }
        }
    }
}
